package adhoc.tel.fer.hr;

import hr.tel.fer.projekt.ContextWeather;

import org.json.JSONException;
import org.json.JSONObject;
import com.xtify.android.sdk.PersistentLocationManager;


import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

/**
 * This service starts Xtify service and handles location changes.
 * Xtify key is sent to main server only once. Location information is 
 * sent to main server on every change.
 */
public class MainService extends Service {
	
	public static String C2D_REGISTRATION = "com.google.android.c2dm.intent.REGISTRATION";

	/** Xtify instance*/
	private PersistentLocationManager persistentLocationManager;
	
	/** Access to system location services.*/
	private LocationManager locationManager;
	
	/** User ID fetched from Facebook.*/
	private String id;
	
	/** Infinite access token fetched from Facebook.*/
	private String accessToken;
	
	/** User name fetched from Facebook.*/
	private String name;
	
	private String locationProvider;
	
	/** Stores current location.*/
	private Location currentLoc;
	
	private Criteria criteria;
	
	private LocationChange locationChange;
	
	public void register() {
		Log.w("C2DM", "start registration process");
		
		PreferencesHelper.initialize(this);
		
		Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
		intent.putExtra("app",
				PendingIntent.getBroadcast(this, 0, new Intent(), 0));
		// Sender currently not used
		intent.putExtra("sender", "zhidor@gmail.com");
		startService(intent);
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		
		// Init location service
		locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
		locationProvider = locationManager.getBestProvider(criteria, true);
		
		// Start Xtify service
		persistentLocationManager = new PersistentLocationManager(getApplicationContext());
		persistentLocationManager.setNotificationDetailsIcon(R.drawable.icon);
		persistentLocationManager.setLocationTracking(false);
		boolean deliverNotifications = persistentLocationManager.isDeliveringNotifications();
		
		if (deliverNotifications) {
			persistentLocationManager.startService();
		}
		
		Log.d("XTIFY KEY", persistentLocationManager.getUserKey());
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		System.out.println("service_started...");
		// Get user information from database
			
		id = adhoc.tel.fer.hr.PreferencesHelper.getFacebookID();
		name = adhoc.tel.fer.hr.PreferencesHelper.getFacebookName();
		accessToken = adhoc.tel.fer.hr.PreferencesHelper.getAccessToken();
			
		Log.d("User information", id + " " + name + " " + accessToken);
		
		// Send key to main server
//		sendXtifyKey();
		
		// Start location service
		locationChange = new LocationChange();
		locationManager.requestLocationUpdates(locationProvider, 3*60*1000, 7, locationChange);
		
		// Send last known location
		if ((currentLoc = locationManager.getLastKnownLocation(locationProvider)) != null){
			sendLocation(currentLoc);
		}	
		return START_FLAG_REDELIVERY;
	}
	
	/**
	 * Current location is packed in JSON object and
	 * sent to the main server.
	 * @param locationToSend Location to be sent.
	 */
	private void sendLocation(Location locationToSend) {
		try {
        	JSONObject location = new JSONObject();
        	
        	double latitude = locationToSend.getLatitude();
        	double longitude = locationToSend.getLongitude();
        	location.put("fb_id", id);
        	location.put("loc_x", latitude);
        	location.put("loc_y", longitude);
            Log.d("LOCATION", id + " " + latitude + " " + longitude + " " );
        	
            Util.sendToServerByPost("location", location);
		}
		  catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}


	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

//	/**
//	 * Xtify key and user informations sre packed to JSON object
//	 * and sent to the main server.
//	 */
//	private void sendXtifyKey(){
//        try {
//        	JSONObject userKey = new JSONObject();
//        	userKey.put("fb_id", id);
//        	userKey.put("name", name);
//        	userKey.put("xtify_id", persistentLocationManager.getUserKey());
//        	userKey.put("accessToken", accessToken);
//        	
//            Log.d("SENT KEY", persistentLocationManager.getUserKey() );
//            Log.d("SENT ID", id );
//            Log.d("SENT NAME", name );
//            Log.d("SENT token", accessToken);
//            
//            Util.sendToServerByPost("init", userKey);
//
//		} catch (JSONException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} 
//	}
		
	
	private class LocationChange implements LocationListener {

		@Override
		public void onLocationChanged(Location location) {
			Log.d("location", "Nova lokacija " + location.getLatitude() + " " + location.getLongitude());
			
			Log.d("location", "determing weather context...");
			ContextWeather.determineWeatherContext(location.getLatitude(), location.getLongitude());
			Log.d("weather_context", "today:"+ContextWeather.today+", tomorrow:"+ContextWeather.tomorrow);
			
			Log.d("location", "sending location...");
			sendLocation(location);
		}

		@Override
		public void onProviderDisabled(String provider) {
			locationProvider = locationManager.getBestProvider(criteria, true);
			System.out.println("Novi provider " + locationProvider);
		}

		@Override
		public void onProviderEnabled(String provider) {}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {}
	}
	
	@Override
	public void onDestroy() {
		locationManager.removeUpdates(locationChange);
		super.onDestroy();
	}
}
